package com.lagou.utils;

import com.alibaba.fastjson.JSON;
import com.lagou.request.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;


public class RpcDecoder extends ByteToMessageDecoder {

    private static int HEAD_LENGTH = 4;

    private Derializer derializer;

    private Class<?> clazz;

    public RpcDecoder(Class<?> clazz, Derializer derializer) {
        this.derializer = derializer;
        this.clazz = clazz;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in,
                          List<Object> list) throws Exception {
        if (in.readableBytes() < HEAD_LENGTH) {
            return;
        }

        in.markReaderIndex();
        int dataLength = in.readInt();
        if (dataLength < 0) {
            ctx.close();
        }
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }

        byte[] body = new byte[dataLength];
        in.readBytes(body);
        Object deserialize = derializer.derializer(clazz, body);
        list.add(deserialize);
    }

    public static void main(String[] args) {
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setMethodName("test");
        byte[] bytes = JSON.toJSONBytes(rpcRequest);
        Object o = JSON.parseObject(bytes, RpcRequest.class);
        System.out.println(o);
    }
}
